/**
 * 用于管理DOM元素和交互的UI工具
 */

class UIManager {
    constructor() {
        this.elements = {};
        this.initElements();
    }

    initElements() {
        // 缓存频繁访问的DOM元素
        this.elements.chatContainer = document.getElementById('chatContainer');
        this.elements.controlsContainer = document.getElementById('controlsContainer');
        this.elements.messagesArea = null;
        this.elements.userInput = null;
        this.elements.sendButton = null;
        this.elements.connectionStatus = null;
        this.elements.systemStatus = null;
        this.elements.lastAction = null;
    }

    /**
     * 渲染聊天组件
     */
    renderChat() {
        // 加载聊天组件HTML
        fetch('components/chat/chat.html')
            .then(response => response.text())
            .then(html => {
                this.elements.chatContainer.innerHTML = html;
                this.initChatElements();
                this.setupChatEventListeners();
                
                // 添加欢迎消息
                this.addMessage("欢迎使用Agentic Jira会议系统！今天我能帮您做什么？", "agent");
            })
            .catch(error => {
                console.error('加载聊天组件时出错:', error);
                this.elements.chatContainer.innerHTML = '<p>加载聊天组件时出错</p>';
            });
    }

    /**
     * 初始化聊天特定元素
     */
    initChatElements() {
        this.elements.messagesArea = document.querySelector('.messages-area');
        this.elements.userInput = document.querySelector('.input-area input');
        this.elements.sendButton = document.querySelector('.input-area button');
    }

    /**
     * 设置聊天事件监听器
     */
    setupChatEventListeners() {
        if (this.elements.userInput && this.elements.sendButton) {
            // 点击按钮发送消息
            this.elements.sendButton.addEventListener('click', () => {
                window.sendMessage();
            });

            // 按Enter键发送消息
            this.elements.userInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    window.sendMessage();
                }
            });
        }
    }

    /**
     * 渲染控制组件
     */
    renderControls() {
        fetch('components/controls/controls.html')
            .then(response => response.text())
            .then(html => {
                this.elements.controlsContainer.innerHTML = html;
                this.initControlsElements();
                this.setupControlsEventListeners();
                this.updateConnectionStatus('connected');
            })
            .catch(error => {
                console.error('加载控制组件时出错:', error);
                this.elements.controlsContainer.innerHTML = '<p>加载控制组件时出错</p>';
            });
    }

    /**
     * 初始化控制特定元素
     */
    initControlsElements() {
        this.elements.connectionStatus = document.getElementById('connectionStatus');
        this.elements.systemStatus = document.getElementById('systemStatus');
        this.elements.lastAction = document.getElementById('lastAction');
    }

    /**
     * 设置控制事件监听器
     */
    setupControlsEventListeners() {
        // 这些事件监听器将由控制组件处理
    }

    /**
     * 向聊天显示区添加消息
     * @param {string} content - 消息内容
     * @param {string} type - 消息类型 (user, agent, system)
     */
    addMessage(content, type = "user") {
        if (!this.elements.messagesArea) {
            console.warn('消息区域未初始化');
            return;
        }

        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${type}-message`;
        messageDiv.textContent = content;
        this.elements.messagesArea.appendChild(messageDiv);
        this.elements.messagesArea.scrollTop = this.elements.messagesArea.scrollHeight;
    }

    /**
     * 更新连接状态指示器
     * @param {string} status - 连接状态 (connected, disconnected, processing)
     * @param {string} message - 可选的状态消息
     */
    updateConnectionStatus(status, message = "") {
        if (!this.elements.connectionStatus) return;

        this.elements.connectionStatus.className = `status-indicator ${status}`;
        
        switch (status) {
            case 'connected':
                this.elements.connectionStatus.textContent = message || "已连接到MCP服务器";
                break;
            case 'disconnected':
                this.elements.connectionStatus.textContent = message || "与MCP服务器断开连接";
                break;
            case 'processing':
                this.elements.connectionStatus.textContent = message || "处理中...";
                break;
            default:
                this.elements.connectionStatus.textContent = message || status;
        }
    }

    /**
     * 更新系统状态
     * @param {string} status - 系统状态文本
     */
    updateSystemStatus(status) {
        if (this.elements.systemStatus) {
            this.elements.systemStatus.textContent = status;
        }
    }

    /**
     * 更新最后操作
     * @param {string} action - 最后操作文本
     */
    updateLastAction(action) {
        if (this.elements.lastAction) {
            this.elements.lastAction.textContent = action;
        }
    }

    /**
     * 切换输入禁用状态
     * @param {boolean} disabled - 是否禁用输入
     */
    toggleInput(disabled) {
        if (this.elements.userInput && this.elements.sendButton) {
            this.elements.userInput.disabled = disabled;
            this.elements.sendButton.disabled = disabled;
        }
    }
}

// 导出供其他模块使用
const uiManager = new UIManager();